<!-- 上传组件封装 -->
<template>
	<div>
		<el-upload class="upload-demo" ref="my-upload" :action="$linkUrl('/admin/upload/addImage')" :on-success="onSuccess"
			:on-remove="handleRemove" :limit="limit" :list-type="listType" :file-list="fileList" :on-exceed="exceed"
			:headers="{Authorization:userInfo}" :on-preview="handlePictureCardPreview">
			<slot name="icon" v-if="isIcon"></slot>
			<i class="el-icon-plus" v-else></i>
		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		// listType :text,picture  文件列表的类型
		// isIcon：是否显示自定义插槽图片
		props: {
			listType: {
				type: String,
				default: 'picture-card'
			},
			isIcon: {
				type: Boolean,
				default: false
			},
			tempImg: {
				type:[String,Array] ,
				default: () => []
			},
			limit: {
				type: [String, Number],
				default: 3
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		watch: {
			fileList:{
				immediate: true,
				handler(v) {
				   if(v.length){
					   
					   let arr=[];
					   this.fileList.forEach(item=>{
						 arr.push(item.url)
					   })
					  this.imageListString=arr.join(',')
				   }else{
					   this.imageListString=''
				   }
				}
			},
			
			tempImg: {
				immediate: true,
				handler(v) {
					
					if (v.length) {
						let newArr = this.changeTempImg(v);
						this.fileList=newArr;
					}else{
						this.fileList=[];
					}
				}
			}
		},
		data() {
			return {
				fileList: [],
				dialogImageUrl: '',
				dialogVisible: false,
				imageListString:''
			}
		},

		methods: {
			changeTempImg(data) {
				return data.map(item => {
					return {
						url: this.$linkUrl(item)
					}
				})
			},
			clearFiles () {
			    this.$refs['my-upload'].clearFiles();
			},
			onSuccess(response, file, fileList) {
				if (!response.data) {
					this.$message.error(response.msg);
				} else {
					this.fileList.push({
						url:this.$linkUrl(response.data)   
					})
				}
				console.log(this.fileList,"this.fileList")
			},
			handleRemove(e) {
				const filePath = e.url;
				const i = this.fileList.findIndex(item => item.url === filePath)
				this.fileList.splice(i, 1)
				console.log(this.fileList,77777)
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			exceed(e) {
				this.$message.error('最多只能上传' + this.limit + '张')
			}


		}
	}
</script>

<style>

</style>
